import React, { useState, useEffect } from 'react';
import { useParams, useModel, Helmet } from 'umi';
import { Carousel } from 'antd';

const Column: React.FC = () => {
	const { word } = useParams<{ word: string }>();
	const [progress, setProgress] = useState(0);
	const [loadFile, setLoadFile] = useState();
	const { columnItem, columnLoading, fetchColumn } = useModel('Column.columnData');
	const column = word ? word : 'home';
	
	useEffect(() => {
		fetchColumn(column);
	}, [column]);
	useEffect(() => {
    if (columnItem) {
      const parser = new DOMParser();
			let html = '';
			let css = '';
			columnItem.sections.forEach((section)=> {
				html += section.html;
				css += section.css;
			});
			html += columnItem.banner.html;
			css += columnItem.banner.css;
      const doc = parser.parseFromString(html, 'text/html');
      const resources = Array.from(doc.querySelectorAll('img, script, link[rel="stylesheet"]'));
resources.push({ tagName: 'LINK', rel : 'stylesheet', href: `/style/${columnItem.id}.css` }); // Add background images to resources
resources.push({ tagName: 'SCRIPT', src: `/js/${columnItem.id}.js` }); // Add background images to resources
//resources.push(...columnItem.banner.map(banneritem => ({ tagName: 'IMG', src: banneritem.litpic }))); // Add background images to resources
			const urlRegex = /url\((['"]?)(.*?)\1\)/g;
        const urls = [];
        let match;
        while ((match = urlRegex.exec(css)) !== null) {
          urls.push(match[2]);
        }
      resources.push(...urls.map(url => ({ tagName: 'IMG', src: url }))); // Add background images to resources
      let loadedResources = 0;
			if(resources.length===0){setProgress(100);}
      const updateProgress = () => {
        loadedResources += 1;
        setProgress(Math.round((loadedResources / resources.length) * 100));
      };
			const head = document.head;
			const body = document.body;
      resources.forEach((resource) => {
        if (resource.tagName === 'IMG') {
					setLoadFile(resource.src);
          const img = new Image();
          img.src = resource.src;
          img.onload = updateProgress;
          img.onerror = updateProgress;
        } else if (resource.tagName === 'SCRIPT') {
					setLoadFile(resource.src);
					for (let i = 0; i < body.children.length; i++) {
						const child = body.children[i];
						if (child.tagName === 'SCRIPT') {
							if (child.getAttribute('src').trim() === resource.src.trim()) {
								return;
							}
						}
					}
          const script = document.createElement('script');
          script.src = resource.src;
          script.onload = updateProgress;
          script.onerror = updateProgress;
          document.body.appendChild(script);
        } else if (resource.tagName === 'LINK' && resource.rel === 'stylesheet') {
					setLoadFile(resource.href);
					for (let i = 0; i < head.children.length; i++) {
						const child = head.children[i];
						if (child.tagName === 'LINK' && child.rel === 'stylesheet') {
							if (child.getAttribute('href').trim() === resource.href.trim()) {
								return;
							}
						}
					}
					const link = document.createElement('link');
          link.rel = 'stylesheet';
          link.href = resource.href;
          link.onload = updateProgress;
          link.onerror = updateProgress;
					document.head.appendChild(link);
        }
      });
    }
  }, [columnItem]);
	useEffect(() => {
    if (columnItem && columnItem.section && Array.isArray(columnItem.section)) {
      columnItem.section.forEach(item => {
        if (item.js) {
          try {
            const executeCode = new Function(item.js);
            executeCode();
          } catch (error) {
            console.error('Error executing dynamic JavaScript code:', error);
          }
        }
      });
    }
  }, [columnItem]);
	
	const now = Math.round(new Date() / 1000);
	if(progress < 100 && now < 1746028800){
		return (
			<>
				<div className="loading">
					<div id="bg"></div>
					<div id="overlay"></div>
					<div id="main">
						<header id="header">
							<p>桥接世界 成就未来</p>
							<h1>企业境外投资一站式服务</h1>
							<nav>
								<ul>
									<li><span>境外投资备案</span></li>
									<li><span>境外企业注册</span></li>
									<li><span>境外银行开户</span></li>
									<li><span>企业税务代缴</span></li>
									<li><span>境外企业审计</span></li>
									<li><span>香港优才计划</span></li>
								</ul>
							</nav>
						</header>
						<footer id="footer">
						</footer>
					</div>
					<div className="loader">
						<div className="text">Loading</div>
						<span className="spinner"></span>
					</div>
				</div>
			</>
		);
	}

	return (
		<>
		{progress === 100 && (
			<>
				{columnItem && (<>
          <Helmet>
            <title>{columnItem.title} </title>
            <meta name="keywords" content={columnItem.keywords} />
            <meta name="description" content={columnItem.description} />

          </Helmet>
					<div className="banner">
            <Carousel autoplay effect="fade">
            { columnItem.banner.map((item, index)=>{
              return (
                <div className="image" key={item.id}>
									{item.html ? <div className='imgbox' dangerouslySetInnerHTML = {{ __html: item.html }} /> : <img src={`${item.litpic}`} /> }
									{item.link && <Link to={item.link}></Link>}
                </div>
              );})}
            </Carousel>
          </div>
					<main>
						{columnItem && columnItem.sections && columnItem.sections.map((item, index)=>{
							return (
								<section className = {item.nameEn} key={index} >
									<div className={item.scw ? "container" : "wcontainer"}>
										{item.h2 && <div className={`stitle ${item.stc && 'stc'}`}>
											<h3>{item.h2}</h3>
											<div className="hr"></div>
											<p>{item.description}</p>
										</div>}
										<div className='scontent' dangerouslySetInnerHTML = {{ __html: item.html }} />
									</div>
								</section>
							);
						})}
					</main>
        </>)}
			</>
		)}
		</>
	);
};

export default Column;